package com.haiwei.poi.common.ex;

import com.google.common.base.Joiner;
import com.haiwei.poi.common.HaiweiStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 将其他类型转换为String
 */
@Slf4j
public class HaiweiExtoStringUtil {
	
	public static final String SPLIT = ",";
	
	private HaiweiExtoStringUtil(){}
	
	/**
	 * 将一个list转换为String
	 * @param list
	 * @return
	 */
	public static String listToString(List<?> list){
		return Joiner.on(SPLIT).join(list); 
	}
	
	/**
	 * 将一个对象List某个属性串联起来
	 * @param list
	 * @param attributte
	 * @param c
	 * @return
	 */
	public static String listToString(List<?> list,String attributte,Class<?> c){
		
		if(CollectionUtils.isEmpty(list)){
			return "";
		}
		
		if( c == null){
			throw new RuntimeException("class can not bean null"); 
		}
		
		try {
			String method = "get" +  HaiweiStringUtil.toUpperCaseFirstOne(attributte);
			Method m = c.getMethod(method);
			
			StringJoiner sj = new StringJoiner(SPLIT);
			list.forEach(o -> {
				
				try {
					Object val = m.invoke(o);
					if(val != null){
						sj.add(val.toString());
					}
				} catch (Exception e) {
					log.error("",e);
				}
				
			});
			return sj.toString();
		} catch (Exception e) {
			log.error("",e);
		}
		return "";
	}
	
	/**
	 * 将一个set转换为String
	 * @param list
	 * @return
	 */
	public static String setToString(Set<?> set){
		return Joiner.on(SPLIT).join(set);
	}

}
